package com.duleme.servlet;

import com.duleme.common.EncodeUtils;
import com.duleme.common.JsonUtils;
import com.duleme.dao.BookDao;
import com.duleme.dao.ShopDao;
import com.duleme.dao.UserDao;
import com.duleme.dao.UserInfoDao;
import com.duleme.entity.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/data/admin")
public class AdminDataServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        EncodeUtils.setEncoding(req,resp);
        String method=req.getParameter("method");
        if (method==null) System.out.println("null");
        else System.out.println(method);
        if(method.equals("user")){
            List<User> list;
            UserDao dao=new UserDao();
            list=dao.findAllUsers();
            BookJson<User> json=new BookJson<>();
            json.setData(list);
            json.setCount(list.size());
            resp.getWriter().print(JsonUtils.toJson(json));
        }else if (method.equals("userInfo")){
            List<UserInfo> list;
            UserInfoDao dao=new UserInfoDao();
            list=dao.findAllUserInfo();
            BookJson<UserInfo> json=new BookJson<>();
            json.setData(list);
            json.setCount(list.size());
            resp.getWriter().print(JsonUtils.toJson(json));
        }else if (method.equals("shop")){
            List<Shop> list;
            ShopDao dao=new ShopDao();
            list=dao.findAllShops();
            BookJson<Shop> json=new BookJson<>();
            json.setData(list);
            json.setCount(list.size());
            resp.getWriter().print(JsonUtils.toJson(json));
        }else if (method.equals("book")){
            List<Book> list;
            BookDao dao=new BookDao();
            list=dao.findAllBooks();
            BookJson<Book> json=new BookJson<>();
            json.setData(list);
            json.setCount(list.size());
            resp.getWriter().print(JsonUtils.toJson(json));
        }else {
            List<String> list=new ArrayList<>();
            BookJson<String> json=new BookJson<>();
            json.setData(list);
            json.setCount(0);
            json.setCode(1);
            resp.getWriter().print(JsonUtils.toJson(json));
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
